package com.cdream.basic.algorithm.leetcode.slideWindow;

import java.util.HashMap;
import java.util.Map;

public class Question560 {
    public static void main(String[] args) {
        System.out.println(new Question560().subarraySum(new int[]{1, 1, 1}, 2));
    }

    // pre[j-1] = pre[i]-k
    public int subarraySum(int[] nums, int k) {
        int pre = 0, count = 0;
        Map<Integer, Integer> mp = new HashMap<>();
        mp.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i];
            count += mp.getOrDefault(pre - k, 0);

            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }

        return count;
    }

    private int slideWindow(int[] nums, int k) {
        int left = 0;
        int right = 0;
        int sum = 0;
        int count = 0;
        while (right <= nums.length - 1) {
            sum += nums[right];
            while (left < nums.length - 1 && sum > k) {
                sum -= nums[left++];
            }
            if (sum == k) {
                count++;
            }
            right++;


        }
        return count;
    }
}
